#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
统一日志系统
提供详细的日志记录功能，支持多种日志级别和输出格式
"""

import logging
import os
from datetime import datetime
from pathlib import Path
from core.utils_module.file_utils import ensure_directory

class ColoredFormatter(logging.Formatter):
    """彩色日志格式化器"""
    
    COLORS = {
        'DEBUG': '\033[36m',    # 青色
        'INFO': '\033[32m',     # 绿色
        'WARNING': '\033[33m',  # 黄色
        'ERROR': '\033[31m',    # 红色
        'CRITICAL': '\033[35m', # 紫色
        'RESET': '\033[0m'      # 重置
    }
    
    def format(self, record):
        # 仅对控制台输出着色，避免污染其他handler的日志内容
        original_levelname = record.levelname
        original_msg = record.msg
        try:
            log_color = self.COLORS.get(record.levelname, self.COLORS['RESET'])
            reset_color = self.COLORS['RESET']
            record.levelname = f"{log_color}{record.levelname}{reset_color}"
            record.msg = f"{log_color}{record.getMessage()}{reset_color}"
            return super().format(record)
        finally:
            # 恢复原始值，避免影响其他handler
            record.levelname = original_levelname
            record.msg = original_msg

def setup_logger(name, level=logging.INFO, log_dir="logs"):
    """
    设置日志器
    :param name: 日志器名称
    :param level: 日志级别
    :param log_dir: 日志文件存放目录
    :return: 配置好的日志器
    """
    
    # 确保日志目录存在
    ensure_directory(log_dir)
    
    # 创建日志器
    logger = logging.getLogger(name)
    logger.setLevel(level)
    
    # 避免重复添加处理器
    if logger.handlers:
        return logger
    
    # 创建文件处理器
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    log_file = os.path.join(log_dir, f"obfuscator_{timestamp}.log")
    file_handler = logging.FileHandler(log_file, encoding='utf-8')
    file_handler.setLevel(logging.DEBUG)
    
    # 创建控制台处理器
    console_handler = logging.StreamHandler()
    console_handler.setLevel(level)
    
    # 创建格式化器
    file_formatter = logging.Formatter(
        '%(asctime)s - %(name)s - %(levelname)s - %(funcName)s:%(lineno)d - %(message)s'
    )
    console_formatter = ColoredFormatter(
        '%(asctime)s - %(levelname)s - %(message)s'
    )
    
    # 设置格式化器
    file_handler.setFormatter(file_formatter)
    console_handler.setFormatter(console_formatter)
    
    # 添加处理器
    logger.addHandler(file_handler)
    logger.addHandler(console_handler)
    
    return logger

class ObfuscationLogger:
    """混淆专用日志记录器"""
    
    def __init__(self, logger):
        self.logger = logger
        self.operation_log = []
        self.statistics = {
            'files_processed': 0,
            'symbols_obfuscated': 0,
            'errors': 0,
            'warnings': 0
        }
    
    def log_operation(self, operation, details):
        """记录操作详情"""
        timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        log_entry = {
            'timestamp': timestamp,
            'operation': operation,
            'details': details
        }
        self.operation_log.append(log_entry)
        self.logger.info(f"[操作] {operation}: {details}")
    
    def log_file_processing(self, file_path, status, details=""):
        """记录文件处理状态"""
        self.statistics['files_processed'] += 1
        self.log_operation("文件处理", f"{file_path} - {status} {details}")
    
    def log_symbol_obfuscation(self, original, obfuscated, file_path=""):
        """记录符号混淆"""
        self.statistics['symbols_obfuscated'] += 1
        self.log_operation("符号混淆", f"{original} -> {obfuscated} {file_path}")
    
    def log_error(self, error_msg, file_path="", line_num=""):
        """记录错误"""
        self.statistics['errors'] += 1
        self.logger.error(f"[错误] {error_msg} {file_path}:{line_num}")
    
    def log_warning(self, warning_msg, file_path="", line_num=""):
        """记录警告"""
        self.statistics['warnings'] += 1
        self.logger.warning(f"[警告] {warning_msg} {file_path}:{line_num}")
    
    def get_statistics(self):
        """获取统计信息"""
        return self.statistics.copy()
    
    def get_operation_log(self):
        """获取操作日志"""
        return self.operation_log.copy()
    
    def save_detailed_log(self, output_path):
        """保存详细日志到文件"""
        ensure_directory(os.path.dirname(output_path))
        
        with open(output_path, 'w', encoding='utf-8') as f:
            f.write("=== 混淆操作详细日志 ===\n\n")
            f.write(f"开始时间: {self.operation_log[0]['timestamp'] if self.operation_log else 'N/A'}\n")
            f.write(f"结束时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n\n")
            
            f.write("=== 统计信息 ===\n")
            for key, value in self.statistics.items():
                f.write(f"{key}: {value}\n")
            f.write("\n")
            
            f.write("=== 操作详情 ===\n")
            for entry in self.operation_log:
                f.write(f"[{entry['timestamp']}] {entry['operation']}: {entry['details']}\n")
